<template>
  <el-drawer
    v-model="drawerVisible"
    :size="650"
    :title="titleMap[mode]"
    @closed="$emit('closed')"
    append-to-body
  >
    <el-container v-loading="saveLoading">
      <el-main>
        <el-form
          :model="form"
          :rules="rules"
          ref="saveForm"
          label-width="140px"
        >
          <el-form-item label="企业名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入企业名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="企业类型" prop="enterpriseType">
            <el-input
              v-model="form.enterpriseType"
              placeholder="请输入企业类型"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="企业属地" prop="block">
            <hh-dict
              v-model="form.block"
              dictType="block"
              placeholder="请选择企业属地"
              clearable
              filterable
            ></hh-dict>
          </el-form-item>
          <el-form-item label="法定代表人" prop="legalPerson">
            <el-input
              v-model="form.legalPerson"
              placeholder="请输入法定代表人"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="unifiedCode">
            <el-input
              v-model="form.unifiedCode"
              placeholder="请输入统一社会信用代码"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="注册资本" prop="regCapital">
            <el-input
              v-model="form.regCapital"
              placeholder="请输入注册资本"
              clearable
            >
              <template #append>万元</template></el-input
            >
          </el-form-item>
          <el-form-item label="注册地址" prop="address">
            <el-input
              v-model="form.address"
              placeholder="请输入注册地址"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="contactNumber">
            <el-input
              v-model="form.contactNumber"
              placeholder="请输入联系电话"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="注册日期" prop="regDate">
            <el-date-picker
              v-model="form.regDate"
              type="date"
              format="YYYY 年 MM 月 DD 日"
              value-format="YYYY-MM-DD"
              placeholder="请选择注册日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="所属行业" prop="industry">
            <el-input
              v-model="form.industry"
              placeholder="请输入所属行业"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item label="缴纳社保信息" prop="insrcInfo">
            <hh-dict
              v-model="form.insrcInfo"
              dictType="insrc_contributions"
              placeholder="请选择缴纳社保信息"
              clearable
              filterable
            ></hh-dict>
          </el-form-item>

          <el-form-item label="缴纳人数" prop="personCount">
            <el-input
              v-model="form.personCount"
              placeholder="请输入缴纳人数"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </el-main>
      <el-footer>
        <div class="form-footer">
          <el-button type="" @click="close">取消</el-button>
          <el-button type="primary" @click="submit">提交</el-button>
        </div>
      </el-footer>
    </el-container>
  </el-drawer>
</template>

<script>
export default {
  name: "enterprise-save",
  emits: ["success", "closed"],
  data() {
    return {
      saveLoading: false,
      drawerVisible: false,
      mode: "add",
      titleMap: {
        add: "新增企业",
        edit: "编辑企业",
      },
      tip: "添加成功",
      form: {
        id: "",
        name: "",
        enterpriseType: "",
        block: "",
        orderNum: "",
        legalPerson: "",
        unifiedCode: "",
        regCapital: "",
        address: "",
        contactNumber: "",
        regDate: "",
        ecoType: "",
        industry: "",
      },
      report: {
        enterpriseId: "",
        finalBlock: "",
      },
      oldBlock: "",
      rules: {
        name: [
          { required: true, message: "请输入企业名称" },
          { min: 0, max: 200, message: "长度必须介于 0 和 200 之间" },
        ],
        enterpriseType: [
          { min: 0, max: 100, message: "长度必须介于 0 和 100 之间" },
        ],
        block: [
          { required: true, message: "请选择企业属地" },
          {
            validator: async (rule, value, callback) => {
              let result = await this.checkDict(value, "block");
              if (result == 0) callback(new Error("请选择企业属地"));
              else callback();
            },
            trigger: "blur",
          },
        ],
        legalPerson: [{ required: true, message: "请输入法定代表人" }],
        unifiedCode: [
          { required: true, message: "请输入统一社会信用代码" },
          {
            pattern: /[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/,
            message: "请输入正确的统一社会信用代码",
            trigger: "blur",
          },
        ],

        address: [{ required: true, message: "请输入注册地址" }],
        contactNumber: [
          { required: true, message: "请输入联系电话" },
          {
            pattern:
              /^([1]\d{10}|([\(（]?0[0-9]{2,3}[）\)]?[-]?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?)$/,
            message: "请输入正确的联系电话",
            trigger: "blur",
          },
        ],
        personCount: [
          {
            pattern: /^(0|\+?[1-9][0-9]*)$/,
            message: "请输入正确的缴纳人数",
            trigger: "blur",
          },
        ],
        regCapital: [
          {
            pattern: /^(0|\+?[1-9][0-9]*)$/,
            message: "请输入正确的注册资本",
            trigger: "blur",
          },
        ],
        insrcInfo: [
          { required: true, message: "请选择缴纳社保信息" },
          {
            validator: async (rule, value, callback) => {
              let result = await this.checkDict(value, "insrc_contributions");
              if (result == 0) callback(new Error("请选择缴纳社保信息"));
              else callback();
            },
            trigger: "blur",
          },
        ],
        regDate: [{ required: true, message: "请选择注册日期" }],
      },
    };
  },
  watch: {
    "form.regDate"(val) {
      console.log("val", val);
    },
  },
  mounted() {},
  methods: {
    //打开
    open(mode = "add") {
      this.mode = mode;
      this.drawerVisible = true;
      return this;
    },
    //修改
    async edit(id) {
      this.tip = "修改成功";
      this.drawerVisible = true;
      this.saveLoading = true;
      let params = { id: id };
      let res = await this.$API.enterprise.details.get(params);
      if (res.code == 0) {
        this.form = res.data;
        this.oldBlock = res.data.block;
        this.saveLoading = false;
      } else {
        let errdata = this.$TOOL.response(res);
        this.$alert(
          this.$TOOL.json.get("", errdata, "message"),
          this.$TOOL.json.get("", errdata, "title"),
          {
            type: "error",
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true,
            showCancelButton: false,
          }
        )
          .then(() => {
            this.drawerVisible = false;
          })
          .catch(() => {});
      }
    },
    //提交
    submit() {
      this.$refs.saveForm.validate(async (valid) => {
        if (valid) {
          let res = {};
          if (this.mode == "add") {
            res = await this.$API.enterprise.save.post(this.form);
          } else {
            if (this.oldBlock != this.form.block) {
              this.report.enterpriseId = this.form.id;
              this.report.finalBlock = this.form.block;
              let res2 = await this.$API.notice.update.post(this.report);
            }
            res = await this.$API.enterprise.update.post(this.form);
          }
          if (res.code == 0) {
            this.$message.success(this.tip);
            //调用父类刷新
            this.$emit("onRefresh");
            this.drawerVisible = false;
          } else {
            let errdata = this.$TOOL.response(res);
            this.$alert(
              this.$TOOL.json.get("", errdata, "message"),
              this.$TOOL.json.get("", errdata, "title"),
              {
                type: "error",
                confirmButtonText: "确定",
                dangerouslyUseHTMLString: true,
                showCancelButton: false,
              }
            );
          }
        }
      });
    },
    //表单注入数据
    setData(data) {
      Object.assign(this.form, data);
    },
    // 关闭页面
    close() {
      this.$emit("closed");
    },
    //检测字典
    async checkDict(dictName, dictType) {
      let params = {
        dictName: dictName,
        dictType: dictType,
      };
      let res = await this.$API.dict.list.get(params);
      return res.data.length;
    },
  },
};
</script>

<style></style>
